const express = require('express');
const router = express.Router();
const db = require('../../../db/index');
const path = require('path');
const fs = require('fs');
//到这的路由为:/admin/news/industryindex/

// 添加分类
// router.get('/acadd',(req,res)=>{

// })
// 渲染文章展示

// 文章添加
router.get('/add', (req, res) => {
  var ac_list;
  var sql = `SELECT * FROM article_classification WHERE is_delete=0`;
  db.query(sql, (err, results) => {
    if (err) {
      return res.send({ code: 1, msg: err.message });
    }
    if (results.length != 0) {
      // console.log(results);
      ac_list = results;
    }
  });
  setTimeout(() => {
    res.render('admin/industryadd', { ac_list });
  }, 500);
});
router.post('/add', (req, res) => {
  // console.log(req.body);
  /* 
   {
  article_name: 'test',
  article_title: 'test1',
  file: '',
  article_pic: '/admin/uploads/undefined-1657636675074.png',
  article_date: '2022-07-15 00:00:00',
  pi_content: '',
  article_content: 'asdasdasdas'
} */
  var { article_name, article_title, article_pic, article_date, article_content, ac_id } = req.body;
  // console.log(banner_show);
  // 在数据库中查重
  var sql = `INSERT INTO article(article_name,article_title,article_pic,article_date,article_content,ac_id) VALUES(?,?,?,?,?,?)`;
  db.query(
    sql,
    [article_name, article_title, article_pic, article_date, article_content, ac_id],
    (err, results) => {
      if (err) return res.send({ code: 0, msg: err.message });

      // 数据库操作发生错误
      if (results.affectedRows == 1) {
        // 受影响行数为1
        return res.send({
          code: 1,
          msg: '插入成功',
        });
      } else {
        return res.send({
          code: 0,
          msg: '插入失败',
        });
      }
    }
  );
});
// router.get('/', (req, res) => {
//   res.render('admin/industryadd');
// });

// 渲染文章展示
router.get('/index', (req, res) => {
  res.render('admin/industrylist');
});
// 文章列表
router.get('/list', (req, res) => {
  let isSearch = req.query.search ? req.query.search : '';
  var count;
  const sqlCount = `select count(*) as count from article  where article_name like "%${isSearch}%"`;
  db.query(sqlCount, (err, result) => {
    if (err) {
      //
      return err.message;
    }
    count = result[0].count;
  });
  // console.log(req.query);
  const { page, limit } = req.query;
  var offset = (page - 1) * limit;

  //SELECT * FROM banner WHERE banner_name LIKE '%${isSearch}%' limit ${offset},${limit}
  var sql = `SELECT * FROM article INNER JOIN article_classification ON article.ac_id=article_classification.ac_id WHERE  article.is_delete=0 AND   article_name LIKE '%${isSearch}%' limit ${offset},${limit}`;
  db.query(sql, (err, results) => {
    if (err) {
      return res.send({ code: 1, msg: err.message });
    }
    if (results !== 1) {
      // console.log(results);
      // console.log(data);
      return res.send({ code: 0, msg: '查询成功', data: results, count: count });
    } else {
      return res.send({ code: 1, msg: '查询成功' });
    }
  });
});
// 文章查看
router.get('/read', (req, res) => {
  // console.log(req.query);
  var { id } = req.query;
  var sql = `select article_id,article_name,article_title,article_date,article_content,article_pic,article_visit,is_show,article.ac_id,article_classification.ac_name FROM article,article_classification WHERE article.ac_id=article_classification.ac_id AND article_id=${id}`;
  db.query(sql, (err, results) => {
    if (err) {
      return res.send({ code: 0, msg: err.message });
    }
    if (results != 0) {
      // console.log(results[0]);

      res.render('admin/article_read', { data: results[0] });
    }
  });
});
// 文章操作中的删除按钮
router.get('/delete', (req, res) => {
  var sql = `update article set is_delete=1 where article_id=${req.query.id}`;
  db.query(sql, (err, results) => {
    if (err) {
      return res.send({ code: 0, msg: err.message });
    }
    if (results.affectedRows == 1) {
      return res.send({ code: 1, msg: '删除成功' });
    } else {
      return res.send({ code: 0, msg: '删除失败' });
    }
  });
});
// update
// 文章操作中的修改按钮
router.get('/update', (req, res) => {
  // res.send('update');
  var article_list;
  var articleClass;
  var sql = `SELECT * FROM article INNER JOIN article_classification ON article.ac_id=article_classification.ac_id WHERE  article.article_id=${req.query.id}`;
  db.query(sql, (err, results) => {
    if (err) {
      return res.send({ code: 0, msg: err.message });
    }
    if (results.length != 0) {
      // 查到了数据
      article_list = results[0];
      // res.render('admin/article_update', { data: results[0] });
    } else {
      return res.send({ code: 0, msg: '查询失败' });
    }
  });
  var articleClassSQL = `SELECT * FROM article_classification`;
  db.query(articleClassSQL, (err, results) => {
    if (err) {
      return res.send({ code: 0, msg: err.message });
    }
    if (results.length != 0) {
      // 查到了数据
      articleClass = results;
    } else {
      return res.send({ code: 0, msg: '查询失败' });
    }
  });
  setTimeout(() => {
    res.render('admin/article_update', { data: article_list, articleClass: articleClass });
  }, 500);
});
// 文章操作中的修改修改提交
// todo:
router.post('/update', (req, res) => {
  var {
    article_id,
    article_name,
    ac_id,
    article_title,
    article_content,
    is_show,
    new_pi_img,
    old_pi_img,
  } = req.body;
  is_show = is_show ? is_show : 0;
  // 1表示删除  0表示未删除
  // if (new_pi_thumb != '' && new_pi_banner != '' && new_pi_img != '') {
  // 说明三个数据全部上传了
  // 替换数据库中的数据 然后删除图片
  var sql = `update article set ac_id=?,article_name=?,article_title=?, article_content=?,is_show=?,article_pic=? where article_id=?`;
  db.query(
    sql,
    [ac_id, article_name, article_title, article_content, is_show, new_pi_img, article_id],
    (err, results) => {
      if (err) return res.send({ code: 0, msg: err.message });
      if (results.affectedRows == 1) {
        // 影响一行  数据库操作成功
        if (new_pi_img != old_pi_img) {
          // 说明修改了图片
          const img_url = path.join(__dirname, '../../../static', old_pi_img);
          fs.unlink(img_url, err => {
            if (err) return res.send({ code: 0, msg: '图片删除失败' });
          });
        }
        return res.send({ code: 1, msg: '修改成功' });
      } else {
        return res.send({ code: 0, msg: '修改失败' });
      }
    }
  );
});
module.exports = router;
